// pages/search/search.js
var request = require("../../requests/api.js");
import util from '../../utils/util.js'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    limitHistoryWords: 30, // 本地搜索记录最大保存数
    searchinput: "", // 搜索框值
    keywords: [] = [], // 服务器热词
    historySearch: [], // 本地搜索记录
    selectedTab: 0, // tab选中的position
    btnStatus: 2, //按钮状态
    keyword: "",
    sort: "onShelfTime",
    order: "asc",
    currentPage: 1,
    pageSize: 10,
    goods: [] = [],
    brands: [] = [],
    searchstate: true, // 展示搜索词 false展示搜索结果
    haveMore: true,
    firstClick: true // 第三个tab是否是第一次点击

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    new app.WeToast();
    var that = this;
    that.getHotWords();
    that.getHistoryWords();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  /**
   * 获取搜索热词
   */
  getHotWords: function() {
    var that = this
    request.getHotWords((res) => {
      that.setData({
        keywords: res.data.hotKeyWords
      })
    }, {}, {})
  },
  /**
   * 获取搜索结果
   */
  getSearchResult: function() {
    var that = this
    var params = {
      keyword: that.data.keyword,
      sort: that.data.sort,
      order: that.data.order,
      currentPage: that.data.currentPage,
      pageSize: that.data.pageSize
    }
    request.getSearchResult(params, (res) => {
      console.log("------length-----------" + res.data.products.length)

      if (res.data.products.length < 10) {
        that.data.haveMore = false
      }
      if (typeof res.data.brands === "undefined") {
        that.setData({
          brands: [],
        })
      } else {
        that.setData({
          brands: res.data.brands,
        })
      }
      that.setData({
        goods: that.data.goods.concat(res.data.products),
        haveMore: that.data.haveMore,
        searchstate: false
      })
    }, (data) => {

      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }

    }, {})

  },
  /**
   * 获取本地缓存搜索记录
   */
  getHistoryWords: function() {
    var that = this;
    wx.getStorage({
      key: 'historySearch',
      success: function(res) {
        var copyHistoryWords = []
        if (res.data.length > that.data.limitHistoryWords) {
          for (var size = 0; size < that.data.limitHistoryWords; size++) {
            copyHistoryWords.push(res.data[size])
          }
        } else {
          copyHistoryWords = copyHistoryWords.concat(res.data)
        }
        that.setData({
          historySearch: copyHistoryWords
        })

      },
      fail: function(res) {
        console.log(res)
      },
      complete: function(res) {
        console.log(res)
      }
    })

  },
  /**
   * 本地储存搜索记录(查重)
   */
  setHistoryWords: function(word) {
    var that = this;
    var index = that.data.historySearch.indexOf(word)
    if (index == -1) { // 不包含
      that.data.historySearch.unshift(word)
    } else {
      // that.data.historySearch.splice(0, 1)
      var removed = that.data.historySearch.splice(index, 1)
      that.data.historySearch.unshift(word)
    }
    that.setData({
      keyword: word,
      historySearch: that.data.historySearch,
      searchinput: word,
      selectedTab: 0,
      goods: [],
      currentPage: 1,
      brands: [],
      searchstate: false,
      haveMore: true
    })
    that.getSearchResult()
    wx.setStorage({
      key: 'historySearch',
      data: that.data.historySearch
    })
  },
  /**
   * 取消
   */
  cansole: function() {
    wx.navigateBack({
      delta: -1
    });
  },
  /**
   * 清空本地数组
   */
  clear_words: function() {
    var that = this;
    that.data.historySearch = []
    that.setData({
      historySearch: that.data.historySearch
    })
    wx.setStorage({
      key: 'historySearch',
      data: that.data.historySearch
    })
  },
  /**
   * 点击热词
   */
  word_click: function(e) {
    var that = this
    var keyword = e.currentTarget.dataset.word;
    that.setHistoryWords(keyword)

  },
  /**
   * 输入法点击搜索
   */
  tosearch: function(e) {
    var that = this
    var word = e.detail.value
    if (word == "") {
      that.wetoast.toast({
        title: '请输入搜索词',
      })
      return
    }
    that.setHistoryWords(word)
  },
  /**
   * 输入法值监听
   */
  bindKeyInput: function(e) {
    this.setData({
      searchstate: true,
    })
  },
  /**
   *清空输入框内容
   */
  clear_input: function() {
    var that = this
    that.setData({
      searchinput: "",
      searchstate: true,
    })
  },
  /**
   * 搜索结果是品牌跳转品牌详情页
   */
  tobrand: function(e) {
    var brandId = e.currentTarget.dataset.brandid;
  
    wx.navigateTo({
      url: '../brandGroup/brandGroup?brandId=' + brandId,
    })
  },
  /**
   * 选中tab项
   */
  changeTab: function(e) {
    var that = this
    var index = parseInt(e.currentTarget.dataset.tabid);
    var status = this.data.btnStatus
    var order = this.data.order;
    var sort = ""
    //如果点击的第三个tab。则更新按钮的状态，
    switch (index) {
      case 0:
        sort = "onShelfTime";
        order = "asc";
        that.data.firstClick = true;
        status = 2
        break
      case 1:
        sort = "sales";
        order = "asc";
        that.data.firstClick = true;
        status = 2
        break
      case 2:
        sort = "price";
        var ss = (order == "asc")
        status = 1
        if (!that.data.firstClick) {
          if (order == "asc") {
            order = "desc"
            status = 0
          } else {
            order = "asc"
            status = 1
          }
        }
        that.data.firstClick = false
        break
    }
    this.setData({
      selectedTab: index,
      currentPage: 1,
      goods: [],
      sort: sort,
      order: order,
      firstClick: that.data.firstClick,
      btnStatus: status,
      haveMore: true
    })
    that.getSearchResult();
  },
  //scrollerview无法触发moredata，所以用这个
  onReachBottom: function(event) {
    this.moreData()
  },
  //上拉触底
  moreData: function() {
    let that = this;
    //如果还有数据就继续加载
    console.log("------ss-----------" + that.data.haveMore)
    if (that.data.haveMore) {
      that.setData({
        currentPage: that.data.currentPage + 1,
      })
      that.getSearchResult()
    }
  },
  // 跳转商品详情页
  toDetailsTap: function(e) {
    var id = e.currentTarget.dataset.productid;
    wx.navigateTo({
      url: '../product/productDetail?productId=' + id,
    })
  },
})